<template>
  <div>
    <div>
      <div class="wrap">
        <!-- <el-select
          v-model="keywords"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading"
          :clearable="true"
          size="mini"
          @change="currentSelect"
          style="width: 500px"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item"
            class="one-text"
          >
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              item.district
            }}</span>
          </el-option>
        </el-select> -->
        <div style="display:flex;">
          <el-input class="inputBtn" v-model="keywords" size="small" placeholder="请输入关键词"></el-input> <el-button type="primary" size="small" style="margin-left:10px;" @click="remoteMethod()">搜索</el-button>
        </div>
        <div class="wrapItem" v-if="options.length>0" >
          <div class="wrapItemIndex" v-for="item in options" :key="item.id" @click="currentSelect(item)">
            <div class="itemName">{{ item.name }}</div>
            <div class="itemDistrict">{{ item.district }}</div>
          </div>
        </div>
      </div>
      <div id="container" class="container"></div>
    </div>
    <div class="info-box">
      <span>经度：{{ form.lng }}</span>
      <span style="padding-left:50px;">纬度：{{ form.lat }}</span>
      <br />
      <!-- <p>详细地址：{{ form.address }}</p> -->
    </div>
  </div>
</template>
 
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  // 安全密钥
  securityJsCode: "7d2251ab85baac5a673a51e6b7245498",
};
export default {
  name: "TestIndex",
  props:{
    center: { 
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      // 地图实例
      map: null,
      // 标记点
      marker: "",
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      // 搜索关键字
      keywords: "",
      // 位置信息
      form: {
        lng: "",
        lat: "",
        address: "",
        adcode: "" //地区编码
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
    };
  },
  computed: {
    getCenter() {
      return (data)=>{
        if(data[0]){
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.form.lng = data[0];
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.form.lat = data[1];
          return [Number(this.form.lng),Number(this.form.lat)]
        }else{
          return null
        }
      }
    }
  },
  created(){
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      AMapLoader.load({
        // 你申请的Key
        key: "da41cf833fef0f7c2cd265dfd5868cbc",
        version: "2.0",
        // 需要用到的插件
        // plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
        plugins: ["AMap.AutoComplete"],
      })
        .then((AMap) => {
          let parm ={
            viewMode: "3D", //是否为3D地图模式
            zoom: 10,//初始化地图级别
          }
          if(this.center[0]){
            parm.center = this.getCenter(this.center) //初始化地图中心点位置
          }
          this.map = new AMap.Map("container", parm);

          //地址逆解析插件
          // this.geoCoder = new AMap.Geocoder({
          //   city: "010", //城市设为北京，默认：“全国”
          //   radius: 1000, //范围，默认：500
          // });
          // 搜索提示插件
          this.AutoComplete = new AMap.AutoComplete({ city: "全国" });

          if(this.form.lng){
            // 清除点
            this.removeMarker();
            // 标记点
            this.setMapMarker();
          }

          //点击获取经纬度;
          this.map.on("click", (e) => {
            // 获取经纬度
            this.form.lng = e.lnglat.lng;
            this.form.lat = e.lnglat.lat;
            // 清除点
            this.removeMarker();
            // 标记点
            this.setMapMarker();
          });

          
        })
        .catch((err) => {
          // 错误
          console.log('错误',err);
        });
    },
    // 标记点
    setMapMarker() {
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat],
      });
      // 逆解析地址
      //this.toGeoCoder();
      this.map.setFitView();
      this.map.add(this.marker);

      this.keywords = "";
      this.options = [];
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    // 逆解析地址 AMap.Geocoder的getAddress方法 | 正向地理编码 对应为AMap.Geocoder的getLocation方法
    // toGeoCoder() {
    //   let lnglat = [this.form.lng, this.form.lat];
    //   this.geoCoder.getAddress(lnglat, (status, result) => {
    //     if (status === "complete" && result.regeocode) {
    //       this.form.address = result.regeocode.formattedAddress;
    //       this.form.adcode = result.regeocode.addressComponent.adcode;
    //     }
    //   });
    // },
    // 搜索
    remoteMethod() {
      let query = this.keywords;
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.AutoComplete.search(query, (status, result) => {
            this.options = result.tips;
          });
        }, 200);
      } else {
        this.options = [];
      }

      // this.options = [{"id":"","name":"西安市","district":"陕西省西安市","adcode":"610112","location":"","address":"未央区","typecode":"190104","city":[]},{"id":"900000124194","name":"西安-华阴","district":"陕西省西安市","adcode":"610100","address":[],"typecode":"999906","city":[]},{"id":"900000124957","name":"西安-高陵","district":"陕西省西安市","adcode":"610100","address":[],"typecode":"999901","city":[]},{"id":"900000124958","name":"西安-高陵","district":"陕西省西安市","adcode":"610100","address":[],"typecode":"999901","city":[]},{"id":"B001D08UZ3","name":"西安站","district":"陕西省西安市新城区","adcode":"610102","location":[108.962723,34.278498],"address":"环城北路48号","typecode":"150200","city":[]},{"id":"B001D09TZP","name":"西安北站","district":"陕西省西安市未央区","adcode":"610112","location":[108.938757,34.37666],"address":"元朔路","typecode":"150200","city":[]},{"id":"B0JBTM52C3","name":"西安西站","district":"陕西省西安市长安区","adcode":"610116","location":[108.756595,34.269633],"address":"沣东新城王寺街道站东一路","typecode":"150200","city":[]},{"id":"B038E0OI0C","name":"西安咸阳国际机场T3航站楼","district":"陕西省咸阳市渭城区","adcode":"610404","location":[108.761401,34.435045],"address":"西安咸阳国际机场内","typecode":"150104","city":[]},{"id":"B038E0OI07","name":"西安咸阳国际机场T1航站楼(暂停营业)","district":"陕西省咸阳市渭城区","adcode":"610404","location":[108.763097,34.442616],"address":"底张镇咸阳国际机场内","typecode":"150104","city":[]},{"id":"B038E0OI05","name":"西安咸阳国际机场T2航站楼","district":"陕西省咸阳市渭城区","adcode":"610404","location":[108.759945,34.440099],"address":"空港大道","typecode":"150104","city":[]}]
    },
    // 选中提示
    currentSelect(val) {
      // 清空时不执行后面代码
      if (!val) {
        return;
      }
      this.form = {
        lng: val.location.lng,
        lat: val.location.lat,
        address: val.district + val.address,
        adcode: val.adcode
      };
      // 清除点
      this.removeMarker();
      // 标记点
      this.setMapMarker();
    }
  }
};
</script>
 
<style scoped>
.container {
  width: 100%;
  height: 500px;
}
.info-box{
  padding-top: 40px;
  font-weight: bolder;
  cursor: pointer;
}

@media screen and (min-width: 750px) {
  .inputBtn{
    width: 50% !important;
  }
}

.wrap{
  padding-bottom: 20px;
  position: relative;
}

.wrapItem{
  position: absolute;
  top: 40px;
  left: 0;
  box-shadow: 2px 0 6px rgba(0, 21, 41, 0.15);
  z-index: 9999 !important;
  background: #fff;
  /* width: 320px; */
  cursor: pointer;
}
.wrapItemIndex{
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-content: center;
  padding: 10px;
  background: #fff;
  box-sizing: border-box;
}
.wrapItemIndex:hover{
  background: #eee;
}

.itemName{
  width: 150px;
  text-align: left;
  color: #000;
}

.itemDistrict{
  /* padding-left: 50px; */
  width: 150px;
  text-align: right;
  color: #99a2ab;
}
</style>